package org.lh.ibernate.core.impl;

import org.lh.ibernate.annotation.Column;
import org.lh.ibernate.annotation.Id;
import org.lh.ibernate.annotation.Table;
import org.lh.ibernate.core.IUpdate;
import org.lh.ibernate.utils.IDbUtil;
import org.lh.ibernate.utils.impl.DbUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class UpdateUtil<T,PK>  implements IUpdate<T,PK> {

    private IDbUtil iDbUtil=new DbUtil();

    @Override
    public void update(Object obj, PK pk) throws Exception {
        Class clazz=obj.getClass();
        StringBuffer sql=new StringBuffer("update ");
        boolean tableNameExist=clazz.isAnnotationPresent(Table.class);
        if(tableNameExist) {
            Object pkValue=new Object();
            String pkName=new String();
            Object fieldValue=new Object();
            Table annoTableName = (Table) clazz.getAnnotation(Table.class);
            String tableName = annoTableName.name(); //获取表名称
            sql.append(tableName+" set ");
            Field[] fields=clazz.getDeclaredFields();
            int length=fields.length;
            int currentIndex=0;
            List<Object> paramsList=new ArrayList<Object>();
            for (Field fieldItem : fields) {
                if(fieldItem.isAnnotationPresent(Id.class)){  //获取id的字段名称
                    Column column=fieldItem.getAnnotation(Column.class);
                    pkName=column.value();
                }
                currentIndex++;
                if(fieldItem.isAnnotationPresent(Column.class)){
                    Column column=fieldItem.getAnnotation(Column.class);
                    String columnName=column.value();
                    String fieldName=fieldItem.getName();
                    String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                    Method getMethod=clazz.getMethod(getMethodName);
                    fieldValue=getMethod.invoke(obj);   //获取每一个column的属性值
                    paramsList.add(fieldValue);
                    if(currentIndex==length){ //到了最后一个属性
                        sql.append(columnName+"=? ");
                    }else{
                        sql.append(columnName+"=?,");
                    }

                }
            }
            paramsList.add(pk);
            sql.append("where "+pkName+"=?");
            System.out.println(sql);
            iDbUtil.executeUpdate(new String(sql),paramsList);
        }
    }
}
